
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:interview/servers/question_list.dart';
import 'package:interview/servers/question_recommends.dart';
import 'package:interview/utils/logger.dart';

class InterviewState {
  final RxList<Question> interviewList = <Question>[].obs;
  final RxBool isFinished = false.obs;
  final RxBool isLoading = false.obs;
  int currentPage = 1;
  int pageTotal = 1;

  void reset() {
    interviewList.clear();
    isFinished.value = false;
    currentPage = 1;
  }
}

class InterviewController {
  final RxMap<String, InterviewState> interviewStateMap = <String, InterviewState>{}.obs;

  /// 获取状态
  InterviewState getInterviewState(String tab) {
    return interviewStateMap.putIfAbsent(tab, () => InterviewState());
  }

  /// 通用的请求方法
  Future<void> _fetchInterviews({
    required BuildContext context,
    required InterviewState state,
    required String tab,
    String? keyword,
  }) async {
    try {
      late QuestionListResponse result;
      if (tab == "推荐") {
        // 请求推荐方法
        result = await fetchRecommendList(context);
      } else{
        final params = QuestionListParams(
          keyword: tab == "最新" ? null : keyword, // "最新" 不传递 keyword
          questionBankType: 9,
          page: state.currentPage,
          pageSize: 10,
          type: 0,
          sort: 0,
        );
        result = await fetchQuestionList(params, context);
      } 
      _handleFetchResult(result, state);
    } catch (e) {
      Logger.error("_fetchInterviews 失败: $e", tag: "_fetchInterviews");
    }
  }

  /// 处理请求结果
  void _handleFetchResult(QuestionListResponse result, InterviewState state) {
    if (result.questions.isNotEmpty) {
      state.interviewList.addAll(result.questions);
      state.pageTotal = result.pageTotal;
      state.currentPage++;
      state.isFinished.value = state.currentPage > state.pageTotal;
    } else {
      state.isFinished.value = true;
    }
  }

  /// 加载更多数据
  Future<void> loadMoreInterViews({
    required BuildContext context,
    required String tab,
    String? keyword,
  }) async {
    final state = getInterviewState(tab);
    if (state.isLoading.value || state.isFinished.value) return;

    state.isLoading.value = true;
    await _fetchInterviews(context: context, tab: tab, state: state, keyword: keyword);
    state.isLoading.value = false;
  }

  /// 刷新数据
  Future<void> refreshInterviews({
    required BuildContext context,
    required String tab,
    String? keyword,
  }) async {
    final state = getInterviewState(tab);
    if (state.isLoading.value) return;

    state.isLoading.value = true;
    state.reset();
    await _fetchInterviews(context: context, tab: tab, state: state, keyword: keyword);
    state.isLoading.value = false;
  }

  
  // 同步详情页点赞数量
  void toggleLikeCount(String tab, String id, RxInt newLikeCount) {
    try {
      final state = getInterviewState(tab);
      final hasQuestion = state.interviewList.any((item) => item.id == id);
      if (!hasQuestion) {
        Logger.warn("未找到 id 为 $id 的 question，跳过更新", tag: "toggleLikeCount");
        return; // 如果不存在，直接返回，避免后续抛出异常
      }
      final question = state.interviewList.firstWhere((item) => item.id == id);
      Logger.info("查看 question $question " ,tag: "toggleLikeCount");
      question.likeCount.value = newLikeCount.value;
      state.interviewList.refresh();
    } catch (e , stackTrace) {
      Logger.error("同步详情页点赞数量: $e", tag: "toggleLikeCount"  , stackTrace: stackTrace );
      rethrow; // 抛出错误
    }
  }

  // 同步详情页浏览量
  void toggleViews(String tab, String id, RxInt newViews){
     try {
      final state = getInterviewState(tab);
      final question = state.interviewList.firstWhere((item) => item.id == id);
      question.views.value = newViews.value;
      state.interviewList.refresh();
    } catch (e) {
      Logger.error("同步详情页浏览量: $e", tag: "toggleLikeCount");
      rethrow; // 抛出错误
    }
  }
}

